import NProgress from "nprogress";

export default class Ajax{
/*
 *  get请求
 *  url:请求地址
 *  data:参数
 *  success:回调函数
 * */
  static get(args){
    if (args.data) {
      let paramsArray = [];
      //拼接参数
      Object.keys(args.data).forEach(key => paramsArray.push(key + "=" + args.data[key]));
      if (args.url.search(/\?/) === -1) {
        args.url += "?" + paramsArray.join("&");
      } else {
        args.url += "&" + paramsArray.join("&");
      }
    }
    NProgress.start();
    //fetch请求
    fetch(args.url,{
      method: "GET",
      mode:args.mode?args.mode:"no-cors",
      credentials: args.credentials?args.credentials:"include",
      headers: args.headers?args.headers:{
        "Content-Type": "application/json"
      },
    })
    .then((response) =>{
      NProgress.done();
      return response.json();
    })
    .then((responseJSON) => {
      args.success(responseJSON);

    })
    .catch(err=>{
      console.log(err);
    });
  }
  /*
   *  post请求
   *  url:请求地址
   *  data:参数
   *  headers:头部
   *  success:回调函数
   * */
  static post(args){
    // args:{url,data,headers,success}
    // 
    // const {act}=args.data;
    // args.url = "".concat(args.url,act);
    // delete(args.data.act);
    const formData = new FormData();
    Object.keys(args.data).forEach(key => formData.append(key,args.data[key]));
    
    NProgress.start();
    //fetch请求
    fetch(args.url,{
      method: "POST",
      headers: args.headers?args.headers:{
        "Content-Type": "application/json"
      },
      mode: "no-cors",
      body:formData,
      credentials: "include",
    })
      .then(response => {
        NProgress.done();
        return response.json();
      })
      .then(json => args.success(json))
      .catch(err=>{
        console.log(err);
      });
  }

 


  // 上传图片
  static upload(args){
    const formData = new FormData();
    const {url,data,success} = args;

    if(data.images && data.images.length){
      data.images.map((item,i)=>{
        console.log(item.file);
        formData.append("file"+i,item.file);
        return false;
      });
      delete data.images;
    }
    NProgress.start();

    Object.keys(data).forEach(key => formData.append(key, data[key]));
    //fetch请求
    fetch(url,
      {
        method: "POST",
        // mode: "no-cors",
        body:formData,
        headers: {
          'Accept': 'application/json'
        }
      })
    .then(response => {NProgress.done();return response.json();})
    .then(json=>success(json))
    .catch((error)=>{
        console.warn(error);
    });
  }
 
}









